/*
http://blog.artera.it/programmazione/html5-upload-di-file-piu-pulito-con-xmlhttprequest2
http://blog.artera.it/materiale/html5-forms/filesystem.js
*/


/* EXAMPLE USAGE */
/*

<form action="/url" id="formid" method="post" enctype="multipart/form-data">
    <b>File</b> <input type="file" class="fileUpload" name="file_field" multiple><br/>
    <button type="submit">Upload</button>
</form>

var fup;
window.addEvent('domready', function(){
    var form = $('formid');
    fup = new MultipartForm(form);
    form.getElements('input[type=file]').forEach( function(el) {new Fileupload(el); }); //fileupload widget
});
*/

var MultipartForm = new Class({
    Implements: Options,
    active:false,
    initialize: function(form, options) {
        this.setOptions(options);

        this.form = form;
        this.form.instance_multipartform = this;

        //this.fileinput = this.form.getElements('input[type=file]');
        this.url = this.form.get('action');

        this.req = new Request.MULTIPART({url:this.url,
                               onLoadstart:this.uploadStart.bind(this),     
                               onProgress:this.uploadProgress.bind(this),     
                               onSuccess:this.uploadComplete.bind(this),
                               onFailure:this.uploadFailed.bind(this),
                               onCancel:this.uploadCanceled.bind(this),
                              });

        this.form.addEvent('submit',function(e) {
            // console.log(this.active);
            e.stop();
            if (this.active) { this.cancel(); }
            else { this.upload(); }
        }.bind(this));

        /**/

        this.progressElement = new Element('div',{'class':'progress'});
        this.progressElement.inject(this.form);
        new Element('progress', {'max':100,'value':0}).inject(this.progressElement);
        new Element('span', {'html':''}).inject(this.progressElement);

        /**/

        this.button = this.form.getElement('button[type=submit]');
        this.deactivate(0,'');

        /**/

    },

    /**/

    activate: function() {
        this.active = true;
        this.button.set('html', 'Stop');
        this.setprogress(0,'Uploading...');
    },
    deactivate: function(progress,text) {
        this.active = false;
        this.button.set('html', 'Upload');
        this.setprogress(progress,text);
    },

    /**/

    setprogress: function(percent,text) {
        this.progressElement.getChildren('progress').set('value', percent);
        this.progressElement.getChildren('span').set('html', text);
    }.protect(),

    /**/

    upload: function(e){
        this.req.send(this.form.getFormItems('formdata'));
    },

    cancel: function(e) {
        this.req.cancel();
    },

    /**/

    uploadStart: function() {
        this.activate();
    },

    uploadProgress: function(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            this.setprogress(percentComplete, percentComplete==100 ? 'Uploading: almost finished' : 'Uploading: ' + percentComplete + '%' );
        }
        else {
            this.setprogress(0,'Uploading...');
        } 
    },

    uploadComplete: function(responseText) {
        // console.log(responseText);
        this.deactivate(100,'Completed');
    },

    uploadFailed: function() {
        this.deactivate(0,'Error during upload');
    },

    uploadCanceled: function() {
        this.deactivate(0,'Aborted by user');
    }
});
